import re
from flask import Flask, request, jsonify
from log_time_sleeps.sql import SQLiteManager


# Flask 应用程序类
class Flask_app():
    def __init__(self):
        self.app = Flask(__name__)
        self.register_routes()

    def register_routes(self):
        # 注册路由
        self.app.add_url_rule('/cookie', view_func=self.post_endpoint, methods=['POST'])

    def find_url_position_and_name(self, url, url_list):
        for index, item in enumerate(url_list):
            # 检查元组中的所有元素是否包含给定的URL
            if url in item:
                return index, item[2]  # 返回数据库表的第三列数
        # 如果没有找到，返回None
        return None, None

    def post_endpoint(self):
        data = request.get_json()
        cookies = data['cookies']
        url = self.url_c(data['URL'])
        db_manager = SQLiteManager()
        url_list = db_manager.select_data()
        position, name = self.find_url_position_and_name(url, url_list)
        if position is not None:
            db_manager.update_data(url, str(cookies), id=position + 1)
        else:
            print(f"{name}未找到URL '{url}'")
        db_manager.close()
        return jsonify(data)

    def find_url_position_and_name(self, url, url_list):
        for index, item in enumerate(url_list):
            # 检查元组中的所有元素是否包含给定的URL
            if url in item:
                return index, item[2]  # 返回数据库表的第三列数
        # 如果没有找到，返回None
        return None, None

    def app_run(self):
        self.app.run(debug=True, port=5555)  # 修改端口号为 5555

    def url_c(self, url):
        match = re.match(r'^(https?://[^/:]+)(?::\d+)?', url)
        host_and_port_with_protocol = match.group()
        return host_and_port_with_protocol


if __name__ == '__main__':
    Flask_app().app_run()
